# -*- coding: utf-8 -*-
"""
用户相关数据验证schemas
@api-version: 1.0.0
"""

from marshmallow import Schema, fields, validate, validates, ValidationError
import re

class LoginSchema(Schema):
    """登录数据验证"""
    email = fields.Email(required=True, validate=validate.Length(max=100), 
                        error_messages={'required': '邮箱不能为空'})
    password = fields.Str(required=True, validate=validate.Length(min=6, max=50),
                         error_messages={'required': '密码不能为空'})

class UserSchema(Schema):
    """用户信息schema"""
    id = fields.Int(dump_only=True)
    username = fields.Str(dump_only=True)  # 保留兼容性，只读
    nickname = fields.Str(required=True, validate=validate.Length(min=2, max=50))
    email = fields.Email(required=True, validate=validate.Length(max=100))
    realName = fields.Str(allow_none=True, validate=validate.Length(max=50), 
                         attribute='real_name', data_key='realName')
    phone = fields.Str(allow_none=True, validate=validate.Length(max=20))
    role = fields.Str(validate=validate.OneOf(['admin', 'user']), default='user')
    status = fields.Int(validate=validate.OneOf([0, 1]), default=1)
    nicknameUpdatedAt = fields.DateTime(dump_only=True, attribute='nickname_updated_at', data_key='nicknameUpdatedAt')
    createdAt = fields.DateTime(dump_only=True, attribute='created_at', data_key='createdAt')
    updatedAt = fields.DateTime(dump_only=True, attribute='updated_at', data_key='updatedAt')
    
    @validates('nickname')
    def validate_nickname(self, value):
        """验证昵称格式"""
        if not re.match(r'^[\u4e00-\u9fa5a-zA-Z0-9_]+$', value):
            raise ValidationError('昵称只能包含中文、字母、数字和下划线')
    
    @validates('phone')
    def validate_phone(self, value):
        """验证手机号格式"""
        if value and not re.match(r'^1[3-9]\d{9}$', value):
            raise ValidationError('手机号格式不正确')

class UserCreateSchema(Schema):
    """创建用户数据验证"""
    nickname = fields.Str(required=True, validate=validate.Length(min=2, max=50))
    email = fields.Email(required=True, validate=validate.Length(max=100))
    password = fields.Str(required=True, validate=validate.Length(min=6, max=50),
                         error_messages={'required': '密码不能为空'})
    realName = fields.Str(allow_none=True, validate=validate.Length(max=50), 
                         attribute='real_name', data_key='realName')
    phone = fields.Str(allow_none=True, validate=validate.Length(max=20))
    role = fields.Str(validate=validate.OneOf(['admin', 'user']), default='user')
    
    @validates('nickname')
    def validate_nickname(self, value):
        """验证昵称格式"""
        if not re.match(r'^[\u4e00-\u9fa5a-zA-Z0-9_]+$', value):
            raise ValidationError('昵称只能包含中文、字母、数字和下划线')
    
    @validates('password')
    def validate_password(self, value):
        """验证密码强度"""
        if not re.match(r'^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d@$!%*?&]{6,}$', value):
            raise ValidationError('密码必须包含字母和数字，长度至少6位')
    
    @validates('phone')
    def validate_phone(self, value):
        """验证手机号格式"""
        if value and not re.match(r'^1[3-9]\d{9}$', value):
            raise ValidationError('手机号格式不正确')

class UserUpdateSchema(Schema):
    """更新用户数据验证"""
    nickname = fields.Str(validate=validate.Length(min=2, max=50))
    realName = fields.Str(allow_none=True, validate=validate.Length(max=50),
                         attribute='real_name', data_key='realName')
    phone = fields.Str(allow_none=True, validate=validate.Length(max=20))
    
    @validates('nickname')
    def validate_nickname(self, value):
        """验证昵称格式"""
        if value and not re.match(r'^[\u4e00-\u9fa5a-zA-Z0-9_]+$', value):
            raise ValidationError('昵称只能包含中文、字母、数字和下划线')
    
    @validates('phone')
    def validate_phone(self, value):
        """验证手机号格式"""
        if value and not re.match(r'^1[3-9]\d{9}$', value):
            raise ValidationError('手机号格式不正确')

class PasswordResetSchema(Schema):
    """密码重置数据验证"""
    newPassword = fields.Str(required=True, validate=validate.Length(min=6, max=50),
                            data_key='newPassword',
                            error_messages={'required': '新密码不能为空'})
    
    @validates('newPassword')
    def validate_password(self, value):
        """验证密码强度"""
        if not re.search(r'[A-Za-z]', value):
            raise ValidationError('密码必须包含字母')
        if not re.search(r'\d', value):
            raise ValidationError('密码必须包含数字')

class AdminUserUpdateSchema(UserUpdateSchema):
    """管理员更新用户数据验证"""
    nickname = fields.Str(validate=validate.Length(min=2, max=50))
    email = fields.Email(validate=validate.Length(max=100))  # 管理员可以修改邮箱
    role = fields.Str(validate=validate.OneOf(['admin', 'user']))
    status = fields.Int(validate=validate.OneOf([0, 1]))
    
    @validates('nickname')
    def validate_nickname(self, value):
        """验证昵称格式"""
        if value and not re.match(r'^[\u4e00-\u9fa5a-zA-Z0-9_]+$', value):
            raise ValidationError('昵称只能包含中文、字母、数字和下划线')